<template>
	<view class="load" v-if="!load">
		<u-loading-icon mode="circle" inactive-color="#fff" text="正在加载..." vertical></u-loading-icon>
	</view>
	<view class="ball_details wap" v-else>
		<view class="top_tip" v-if="msg">{{msg}}</view>

		<!-- 顶部 -->
		<view class="ball_top">
			<block v-if="cover">
				<imgbox width="100%" height="560rpx" mode="aspectFill" :src="cover" />
			</block>

			<view class="con">
				<view class="title f1 c1">{{resData.Title}}</view>
				<view class="info f2 c3">{{resData.Remark}}</view>
			</view>
		</view>
		<!-- 发起者 场地 -->
		<view class="ball_site">
			<view class="site_hd">
				<view class="left">
					<view class="cover">
						<image :src="resData.HeadImgUrl" mode="aspectFill" />
					</view>
					<view class="f1 c1 name">{{ resData.TrueName || '匿名' }} <text class="f2 c3 pl8">发起</text></view>
				</view>
				<view class="right">
					<text class="f3 c_sed pl10">{{getTime2(resData.ServerDate) +" " +getWeek(resData.ServerDate)}}
						{{resData.ServerTime}}</text>
				</view>
				<!-- <view class="right" v-else>
					<text class="f1 c_sed">免费</text> 
				</view> -->
			</view>
			<view class="p20">
				<view class="site_bd">
					<view class="site_con">
						<view v-if="resData.ShopLogo" class="logo">
							<image :src="resData.ShopLogo" mode="" />
						</view>
						<view class="f1 c1 name">
							{{resData.ShopID>0?resData.ShopName:resData.Place}}
						</view>
						<view class="t_price"><text class="f3 c_sed ">距离：{{resData.Distance}} KM</text> </view>
					</view>
					<view v-if="resData.ShopAddress" class="site_add f2 c3">
						<uni-icons type="location" size='14' color="#fff"></uni-icons>
						{{resData.ShopAddress}}
					</view>
				</view>
				<view class="site_ft">
					<text class="f2 c1">买单方式：</text><text class="f2 c2">{{resData.FeeRule}}</text>
				</view>
			</view>

		</view>
		<!-- 参与者  -->
		<view class="participate">
			<view class="participate_con">
				<view class="item_tow" v-for="(itemTow,ind) in resData.Item" :key="ind">
					<view class="cover cover_sed">
						<image :src="itemTow.HeadImgUrl" mode="" />
					</view>
					<view class="name d1">{{itemTow.TrueName || "匿名"}}</view>
					<view class="f2 c2 c_sed mt5" v-if="itemTow.Status == 2">已签到</view>
				</view>
			</view>
		</view>

		<!-- 操作 状态 -->

		<view class="bottom_status" v-if="resData.Status == 0">
			<view class="flx wap" @click="cancelBall">
				取消报名
			</view>
		</view>
		<view class="bottom_status" v-if="is_sign">
			<view class="flx wap">
				<view class="btn" @click="signUser">开始签到</view>
			</view>
		</view>
	</view>
</template>

<script>
	import imgbox from "@/pages/ball/components/imgbox/imgbox.vue";
	export default {
		components: { imgbox },
		data() {
			return {
				isBaomin: "",
				msg: "",
				joinMe: false,
				load: false,
				// 同组人员
				selectApplyList: [],
				// 已经勾选的同组人员
				applyList: [],
				payID: "",
				ID: null,
				payPrice: 0,
				isPay: false,
				cover: "",
				user: {},
				load: false,
				resData: {},
				read: false,
				userIDList: [],
				is_sign: false,
				passNum: 0,
				Latitude: '',
				Longitude: ''
			}
		},
		async onLoad(e) {
			this.ID = e.id;
			if (await this.$store.getters.getLoginState) {
				this.getCity();

				await this.init();
			}
		},
		methods: {
			async cancelBall() {
				let _this = this;
				uni.showModal({
					title: '温馨提示',
					content: '您确认要取消报名吗',

					showCancel: false,
					success: async function(res) {
						if (res.confirm) {
							_this.$pv.load()
							let r = await _this.$api.post('Appointment/UserCancel', { AppointmentID: _this.ID });
							setTimeout(() => {
								_this.$pv.msg('已取消');
								this.init();
							}, 500)

						}
					}
				});
				// api/Appointment/UserCancel
			},
			getLocationSysc() {
				let _this = this;
				return new Promise((resolve, reject) => {
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							resolve(res)
						},
						fail: function(err) {
							const defaultLocation = {
								latitude: 0,
								longitude: 0
							};
							resolve(defaultLocation);
						}
					});
				})

			},
			async getCity() {
				let loc = await this.getLocationSysc();
				this.Longitude = loc.longitude;
				this.Latitude = loc.latitude;
			},
			async signUser() {
				const l = this.resData
				if (!this.Latitude || !this.Longitude) {
					this.getCity()
					return this.$pv.msg('您的位置未受权')
				};
				if (l.Latitude && l.Longitude) {
					const { distance } = this.$util.getDistances(l.Latitude, l.Longitude, this.Latitude, this.Longitude);
					if (Math.abs(distance) > 100) return this.$pv.msg('签到地点超出范围')
				}
				this.$pv.load('正在处理')
				let res = await this.$api.post('Appointment/UserSign', { AppointmentID: this.ID });
				this.init()
				this.$pv.msg('签到成功');
			},
			changeUser(e) {
				let arr = e.detail.value;
				this.applyList.forEach(async item => {
					if (arr.indexOf(item.ID + '') != -1) {
						await this.audit(item.ID, 1)
					} else {
						await this.audit(item.ID, 0)
					}
				})
			},
			async closeUser(id) {
				await this.audit(id, 0)
			},
			// 取消组局
			// api/Appointment/Cancel
			async cancal() {
				this.$pv.load('正在取消组局');
				let res = await this.$api.post('Appointment/Cancel', { ID: this.ID });
				setTimeout(() => {
					this.$pv.closeLoad();
					this.$pv.msg('已取消');
					this.init();
				}, 1000)

			},
			// 完成组局
			// api/Appointment/FinishAppointment
			async funish() {
				this.$pv.load('正在处理')
				let res = await this.$api.post('Appointment/FinishAppointment', { ID: this.ID });
				setTimeout(() => {
					this.nav_to(`/pages/ball/ball_user_success?id=${this.ID}`)
				}, 1000)
			},
			// api/Appointment/ServerAppointment
			async ServerAppointment() {
				this.$pv.load('正在处理')
				let res = await this.$api.post('Appointment/ServerAppointment', { ID: this.ID });
				setTimeout(() => {
					this.init();
					this.$pv.msg('已为您通知客服订单');
				}, 1000)

			},
			async balancePay(isPay) {
				// this.payPrice = 0.01;
				let _this = this;
				// 有余额
				if (isPay) {
					// EventType == "订场"
					// EventID=0
					// PayUserType=场地名称
					// PayFee=金额
					let data = {
						PayFee: this.payPrice,
						EventType: '订场',
						PayUserType: this.resData.ShopName,
						EventID: this.payID,
						PayScore: 0
					}
					console.log(data);
					this.$pv.load('正在处理');
					let res = await this.$api.post('Payment/BaPay', data);
					this.$pv.closeLoad();
					if (res.code == 0) {
						setTimeout(() => {
							_this.init()
						}, 1000)
					} else {

					}

				} else { // 余额不足
					let pres = await this.$api.post('/Payment/PayV2', {
						EventID: this.payID,
						CompanyID: 6002,
						total_fee: this.payPrice,
						EventType: '定场',
						body: this.shop.ShopName,
						SourcePage:'ball_details_attend',
						// #ifdef MP-WEIXIN
						PayChannel: "weixin",
						// #endif
						// #ifdef APP
						PayChannel: "app"
						// #endif
					})

					let payObj = JSON.parse(pres.data);
					uni.requestPayment({
						provider: 'wxpay',
						// #ifdef APP
						orderInfo: payObj,
						// #endif
						// #ifdef MP-WEIXIN
						timeStamp: payObj.timeStamp,
						nonceStr: payObj.nonceStr,
						package: payObj.package,
						signType: payObj.signType,
						paySign: payObj.paySign,
						// #endif
						success: async function(res) {

							setTimeout(() => {
								_this.init()
							}, 1000)
						},
						fail: function(err) {
							_this.$pv.msg('支付失败');
						}
					});
				}
			},
			setRead() {
				this.read = !this.read;
			},

			openPay() {
				this.$refs.cpay.open();
			},
			async init() {
				this.user = uni.getStorageSync('user');

				let res = await this.$api.post('Appointment/Detail', { ID: this.ID, User_Lat: this.Latitude, User_Lng: this
						.Longitude });
				this.resData = res.data;
				this.userIDList = res.data.Item.map(item => item.UserID);

				if (Array.isArray(JSON.parse(res.data.Images)) && JSON.parse(res.data.Images).length > 0) {
					this.cover = JSON.parse(res.data.Images)[0]
				} else {
					this.cover = ""
				}
				this.passNum = 0;

				this.applyList = [];
				this.resData.Item.forEach(item => {
					if (item.Status == 1) {
						this.passNum++;
					}
					if (item.UserID == this.user.UserID) {
						this.payPrice = item.Price;
						this.isPay = item.PayStatus == 1;
						this.payID = item.ID;
						this.is_sign = item.Status == 1 ? true : false;
					}
					if (item.UserID != this.resData.UserID) {
						this.applyList.push(item);
					}
				});
				this.selectApplyList = [];
				this.resData.Item.forEach(item => {
					if (item.Status == 1) {
						this.selectApplyList.push(item);
					}
				})

				this.joinMe = false;
				this.resData.Item.forEach(item => {
					if (item.UserID == this.user.UserID) {
						console.log(item)
						if (item.Status == 1) {
							this.joinMe = true;
						}
					}
				})


				// 头部提示文字
				// 头部提示文字
				if (this.resData.Status == -1) {
					this.msg = "已经取消"
				} else if (this.resData.Status == 1) {
					this.msg = "进行中";
				} else if (this.resData.Status == 0) {
					this.msg = "报名中";
				} else if (this.resData.Status == 2) {
					this.msg = "运动结束";
				} else {
					this.msg = "";
				}

				// -2未报名 0报名 -1取消报名 2 我发起的
				if (Array.isArray(this.resData.Item)) {

					this.resData.Item.forEach(item => {
						if (item.UserID == this.user.UserID && item.Status == 0) {
							this.isBaomin = 0
						} else if (item.UserID == this.user.UserID && item.Status == -1) {
							this.isBaomin = -1
						}
					});
				}

				if (this.isBaomin == -1) {
					this.msg = "已取消报名";
				}



				this.load = true;
			},
			async join() {
				this.$pv.load();
				let res = await this.$api.post('Appointment/AddItem', {
					ID: this.resData.ID,
					Price: this.resData.Price,
					PeopleNum: this.resData.PeopleNum
				});
				setTimeout(() => {
					this.$pv.msg('已经为您提交');
					this.init()
				}, 1000)

			},
			async audit(itemID, Status) {
				// this.$pv.load('正在处理');
				// 需要{{resData.PeopleNum}}人,已有{{passNum}}

				if (this.PeopleNum == this.passNum) {
					this.$pv.msg('已满员');
				}

				let res = await this.$api.post('Appointment/AuditItem', {
					ID: itemID,
					AppointmentID: this.resData.ID,
					Status: Status
				})
				setTimeout(() => {
					this.init();
				}, 200)
			}
		},
		computed: {

			getTime2() {
				return l => {
					let d = new Date(l);
					let timestamp = d.getTime();
					return this.$u.date(timestamp, 'mm-dd');
				}
			},
			getWeek() {
				return l => {
					let d = new Date(l);
					let week = d.getDay();
					let weelStr = week == 0 ? '星期天' : week == 1 ? '星期一' : week == 2 ? '星期二' : week == 3 ? '星期三' : week == 4 ?
						'星期四' : week == 5 ? '星期五' : '星期六';
					return weelStr;
				}
			}
		},
		onShareAppMessage(e) { //发送给朋友
			// let trendsIndex = e.target.dataset.trendsIndex;			

			let shareTitle = this.resData.Title;
			let pid = uni.getStorageSync('user').UserID;
			let sharePath = `pages/ball/ball_details?id=${this.resData.ID}&pid=${pid}`;
			let imageUrl = JSON.parse(this.resData.Images)[0];
			return {
				title: shareTitle,
				path: sharePath,
				imageUrl: imageUrl
			}
		},
	}
</script>

<style lang="scss">
	.ball_details {
		padding-bottom: 200rpx;

		.p20 {
			padding-left: 20rpx;
			padding-right: 20rpx;
		}

		.ball_top {
			margin-top: 20rpx;
			border-radius: 16rpx;
			overflow: hidden;
			background: #202020;

			.con {
				padding: 20rpx;

				.title {
					line-height: 1.8;
				}

				.info {
					line-height: 1.8;
				}
			}
		}

		.ball_site {
			margin-top: 20rpx;
			background: #202020;
			border-radius: 16rpx;
			overflow: hidden;

			.site_hd {
				height: 100rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-left: 20rpx;
				padding-right: 20rpx;
				background: #262626;
				border-radius: 16rpx;

				.left {
					display: flex;
					align-items: center;
				}

				.cover {
					height: 70rpx;
					width: 70rpx;
					border: 1px solid #7B7B7B;
					border-radius: 50%;
					overflow: hidden;
					margin-right: 16rpx;

					image {
						height: 100%;
						width: 100%;
					}
				}

				.cover_sed {
					border: 1px solid #DCC188;
				}

				.name {
					margin-right: 8rpx;
				}

			}

			.site_bd {
				padding-top: 32rpx;
				padding-bottom: 32rpx;

				border-bottom: 1px solid #404040;

				.site_con {
					display: flex;
					align-items: center;

					.logo {
						margin-right: 10rpx;
						height: 48rpx;
						width: 48rpx;

						image {
							height: 100%;
							width: 100%;
							border-radius: 50%;
						}
					}
				}

				.site_add {
					margin-top: 20rpx;
				}
			}

			.site_ft {
				padding-top: 20rpx;

				padding-bottom: 20rpx;
				line-height: 1.8;
			}
		}

		.participate {
			padding-top: 12rpx;
			margin-top: 10rpx;
			background: #262626;
			border-radius: 16rpx;

			.tcen {
				text-align: center;
			}

			.b_left {
				position: relative;

				&::after {
					position: absolute;
					top: 0;
					left: 0;
					content: "";
					height: 100%;
					width: 1px;
					background: #7B7B7B;
				}
			}

			.participate_con {

				padding-bottom: 22rpx;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				padding-left: 20rpx;
				padding-right: 20rpx;

				.item_tow {
					width: 100rpx;
					margin-right: 30rpx;

					&:nth-child(5n + 1) {
						margin-right: 0;
					}
				}


				.cover {
					margin-top: 40rpx;
					height: 100rpx;
					width: 100rpx;
					border-radius: 50%;
					border: 1px solid #7B7B7B;
					overflow: hidden;

					image {
						height: 100%;
						width: 100%;
					}
				}

				.name {
					margin-top: 10rpx;
					font-size: 24rpx;
					text-align: center;
				}

				.cover_icon {
					display: flex;
					justify-content: center;
					align-items: center;

					image {
						height: 60rpx;
						width: 60rpx;
					}
				}
			}

		}

		.bottom_status {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			background: #1C1C1C;
			box-sizing: border-box;

			.price {
				width: 300rpx;
				padding-left: 20rpx;
				padding-right: 20rpx;
			}

			.flx {
				display: flex;
				justify-content: space-between;
				height: 140rpx;
				align-items: center;
			}

			.right {
				width: 290rpx;
				height: 84rpx;
				line-height: 84rpx;
			}

			.rd {
				margin-top: 10rpx;
			}

			.btn {
				flex: 1;
			}
		}
	}

	.mt20 {
		margin-top: 20rpx;
	}

	.pl8 {
		padding-left: 8rpx;
	}

	.pl10 {
		padding-left: 10rpx;
	}

	.btn_grey {
		background: #aaa;
		color: #ccc;
	}

	.top_tip {
		margin-top: 32rpx;
		height: 70rpx;
		background: rgba(254, 240, 188, 0.2);
		border-radius: 4rpx;
		color: #FEF0BC;
		line-height: 70rpx;
		text-align: center;
		margin-bottom: 30rpx;

	}
</style>